// components/userInfo.js
const app = getApp()
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        isLogin: true
    },

    /**
     * 组件的方法列表
     */
    methods: {
        getUser(res) {
            const info = res.detail
            const ps = getCurrentPages()
            const currentPage = ps[ps.length - 1]
            const is_examine = wx.getStorageSync('PROGRAM_VERIFY')
            if (!is_examine) return
            if (info.errMsg === "getUserInfo:ok") {
                let user = {
                    name: info.userInfo.nickName,
                    image: info.userInfo.avatarUrl
                }
                this.saveInfo(user)
            } else {
                is_examine != "1" && wx.navigateTo({
                    url: '/pages/common/get-phone',
                })
            }
        },
        saveInfo(user) {
            wx.showLoading({
                title: '登录中...',
            })
            app.http.post('rest/member/perfect.do', {
                data: user
            }).then(res => {
                wx.setStorage({
                    key: 'user',
                    data: user,
                    success: res => {
                        this.setData({
                            isLogin: true,
                        })
                        let page = getCurrentPages()
                        let currentPage = page[page.length - 1]
                        currentPage.setData({
                            user: wx.getStorageSync('user')
                        })
                        currentPage.onLoad(currentPage.options)
                    }
                })
                wx.hideLoading()
            }).catch(err => {
                wx.removeStorageSync('user')
            })
        },
    },
    attached() {
        let user = wx.getStorageSync('user')
        if (user) {
            this.setData({
                isLogin: true,
            })
        } else {
            app.toPromise(wx.getSetting).then(res => {
                if (res.authSetting['scope.userInfo']) {
                    wx.getUserInfo({
                        success: res => {
                            let user = {
                                name: res.userInfo.nickName,
                                image: res.userInfo.avatarUrl
                            }
                            this.saveInfo(user)
                        }
                    })
                } else {
                    this.setData({
                        isLogin: false,
                    })
                }
            })
        }
    }
})